<template>
  <div class="userAdminContent">
    <a-layout>
      <a-layout-content
          :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
      >

        <p class="adminUserHeader">
          <a-form layout="inline" :model="param">
            <a-form-item>
              <a-input v-model:value="param.loginName" placeholder="请输入想查询的用户" >
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button  @click="handleQuery({page: 1, size: pagination.pageSize})" shape="round">
                <SearchOutlined />
              </a-button>
            </a-form-item>
            <a-form-item>
              <a-button  @click="add()" shape="round">
                <user-outlined />
                创建用户
              </a-button>
            </a-form-item>
          </a-form>
        </p>

        <a-table
            :data-source="users"
            :columns="columns"
            :row-key="record => record.id"
            :pagination="pagination"
            :loading="loading"
            @change="handleTableChange">

          <template v-slot:action="{ text, record }" >
            <a-space size="small">
              <a-button  @click="resetPassword(record)" shape="round">
                <edit-outlined />
                重置密码
              </a-button>
              <a-button  @click="edit(record)" shape="round">
                <edit-outlined />
                编辑
              </a-button>
              <a-popconfirm
                  title="删除后不可恢复，确认删除?"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="handleDelete(record.id)"
              >
                <a-button  shape="round">
                  <delete-outlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table>
      </a-layout-content>
    </a-layout>
  </div>

  <a-modal
      title="用户表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
  >
    <a-form :model="user" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="登陆名">
        <a-input v-model:value="user.loginName" :disabled="!!user.id"/>
      </a-form-item>
      <a-form-item label="昵称">
        <a-input v-model:value="user.name" />
      </a-form-item>
      <a-form-item label="密码" v-show="!user.id">
        <a-input v-model:value="user.password" type="password"/>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
      title="重置密码"
      v-model:visible="resetModalVisible"
      :confirm-loading="resetModalLoading"
      @ok="handleResetModalOk"
  >
  <a-form :model="user" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
    <a-form-item label="新密码">
      <a-input v-model:value="user.password" type="password"/>
    </a-form-item>
  </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, onMounted,ref } from 'vue';
import axios from 'axios';
import { message } from "ant-design-vue";
import { Tool } from '@/util/tool';
import { SearchOutlined } from '@ant-design/icons-vue';

// declare相当于告诉这个文件，hexMd5和KEY这两个变量是存在的(如果要用第三方的js里面的一些变量的话，可以用这种方法声明变量)
declare let hexMd5: any;
declare let KEY: any;

export default defineComponent({
  name:'AdminUser',
  setup() {
    // 定义响应式变量searchUser
    const param = ref();
    param.value={};
    const users = ref();
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0
    });
    const loading = ref(false);

    const columns = [
      {
        title: 'id',
        dataIndex: 'id'
      },
      {
        title: '登陆名',
        dataIndex: 'loginName'
      },
      {
        title: '名称',
        dataIndex: 'name'
      },

      {
        title: '',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ];
    /**
     * 数据查询,前后端分页同步
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      users.value = [];
      axios.get("/user/list",({
        params:{
          page:params.page,
          size:params.size,
          loginName: param.value.loginName
        }
      })).then((response) =>{

        loading.value=false;
        const data = response.data;
        if (data.success){
          // 显示密码时用
          users.value= data.content.list;

          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        }else {
          message.error(data.message);
        }
      });
    };

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      console.log("看看自带的分页参数都有啥：" + pagination);
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    };



    // -------表单--------
    /**
     * 数组，[100, 101]对应：前端开发 / Vue
     */

    const user= ref();
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const handleModalOk = () => {
      // 点击ok先显示loading效果
      modalLoading.value = true;
      // 对用户密码进行加密
      user.value.password = hexMd5(user.value.password + KEY);
      axios.post("/user/save", user.value).then((response) => {

        modalLoading.value = false;
        // 当post请求发送以后，值返回时执行以下操作
        const data = response.data;
        if (data.success){ // data = CommonResp,所以有success属性
          // 如果保存成功，取消loading效果，关闭对话框

          modalVisible.value = false;

          // 关闭对话框后重新加载列表
          handleQuery({
            page:pagination.value.current, // 加载当前所在页
            size:pagination.value.pageSize
          })
        }else {
          message.error(data.message);
        }

      });
    };


    // 编辑功能，点击编辑按钮时触发的事件
    const edit = (record:any) => {
      // 显示模态框
      modalVisible.value = true;
      user.value = Tool.copy(record);
    };

    // 新增功能，点击新增按钮时触发的事件
    const add = () => {
      modalVisible.value = true;
      user.value = {}
    };

    const level1 =  ref();
    let categorys: any;


    // 删除功能，点击删除按钮时触发的事件
    const handleDelete = (id:number) =>{
      axios.delete("/user/delete/"+ id).then((response) => {

        // 当delete请求发送以后，值返回时执行以下操作
        const data = response.data;
        if (data.success){ // data = CommonResp,所以有success属性
          // 如果删除成功，直接重新加载列表
          handleQuery({
            page:pagination.value.current, // 加载当前所在页
            size:pagination.value.pageSize
          })
        }
      });
    };

    // -------- 重置密码 ---------
    const resetModalVisible = ref(false);
    const resetModalLoading = ref(false);
    const handleResetModalOk = () => {
      resetModalLoading.value = true;

      user.value.password = hexMd5(user.value.password + KEY);

      axios.post("/user/reset-password", user.value).then((response) => {
        resetModalLoading.value = false;
        const data = response.data; // data = commonResp
        if (data.success) {
          resetModalVisible.value = false;

          // 重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          message.error(data.message);
        }
      });
    };

    /**
     * 重置密码
     */
    const resetPassword = (record: any) => {
      resetModalVisible.value = true;
      user.value = Tool.copy(record);
      user.value.password = null;
    };

    /**
     * 根据name查询电子书信息
     */
    // const handleQueryByName = (params: any) => {
    //   loading.value = true;
    //   users.value = [];
    //   axios.get("/user/search", {
    //     params: {
    //       page: params.page,
    //       size: params.size,
    //       loginName: param.value.loginName
    //     }
    //   }).then((response) => {
    //
    //     loading.value = false;
    //     const data = response.data;
    //     if (data.success) {
    //       users.value = data.content.list;
    //       // 重置分页按钮
    //       pagination.value.current = params.page;
    //       pagination.value.total = data.content.total;
    //     } else {
    //       message.error(data.message);
    //     }
    //   })
    // };

    onMounted(()=>{
      handleQuery({
        page: 1,
        size: pagination.value.pageSize,
      });
      // handleQueryCategory();
    });

    return{
      // 表格用到的返回参数
      param,
      users,
      pagination,
      columns,
      loading,
      handleTableChange,

      //搜索功能用到的返回参数
      handleQuery,

      // 新增和编辑
      edit,
      add,

      // 表单用到的返回参数
      user,
      modalVisible,
      modalLoading,
      handleModalOk,

      handleDelete,

      // 修改密码用到的返回参数
      resetModalVisible,
      resetModalLoading,
      handleResetModalOk,
      resetPassword
    }
  },
});
</script>
<style scoped>
.userAdminContent{
  text-align: center;
  margin: 15px 200px 10px;
}
.adminUserHeader{
  margin: 15px 310px 10px;

}
</style>